package sctu.edu.java.year2016.team01.lishuai.day20160606.chapter12_1;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by 李大帅 on 2016/6/5.
 * 实现读取文件时出现一个表示进度的进度条，可使用ProgressMonitorInputStream。。
 */
public class ProgressMonitorTest extends JFrame{

    public static void main(String[] args) throws IOException, InterruptedException {

        JFrame jl = new JFrame("读取文件进度条");
        Container container=jl.getContentPane();
        container.setLayout(new FlowLayout());
        jl.setSize(300, 300);
        jl.setVisible(true);
        jl.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        ProgressMonitorInputStream monitor;
        monitor = new ProgressMonitorInputStream(jl,"读取数据",new FileInputStream("D:\\WWW.docx"));
        ProgressMonitor progressMonitor = monitor.getProgressMonitor();

        int read_unit = 4;//设置每次读取的字节数
        int all = monitor.available();//得到目标文件的总子节数
        int readed = 0;//每次实际读取到的字节数

        byte[] data = new byte[read_unit];//字节数组，保存读取到的字节数

        while (monitor.available()>0)
        {
            Thread.sleep(10);

            int in = monitor.read(data);
            readed+=in;
            float process = (float)readed/all*100;//算出百分百
            progressMonitor.setNote("archived:"+process+"%");
        }
    }
}
